package com.dingreading.cloud.admin.controller;

import com.alibaba.fastjson.JSONArray;
import com.dingreading.cloud.admin.entity.CourseTypes;
import com.dingreading.cloud.admin.service.CourseService;
import com.dingreading.cloud.admin.service.CourseTypesService;
import com.dingreading.cloud.admin.util.TreeJsonUtil;
import com.dingreading.cloud.admin.util.bean.CourseUtil;
import com.dingreading.cloud.admin.util.redis.RedisService;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.NepUtil;
import com.dingreading.cloud.common.util.RedisParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/system/courseTypes/v2")
@Api(tags = "总部-学院视频的分类管理")
public class CourseTypesControllerV2 {

    @Resource
    protected CourseTypesService courseTypesService;
    @Resource
    protected CourseService courseService;
    @Resource
    protected RedisService redisService;


    @ApiOperation(value = "分类tree")
    @PostMapping(value = "/treeList")
    public R<Object> treeList(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "主分类id") @RequestParam(value = "id", required = false) Long id
    ) {
        JSONArray treeJson = new JSONArray();
        List<CourseTypes> courseTypesList;
        if (id != null && id > 0) {
            courseTypesList = courseTypesService.getByMainId(id);
        } else {
            courseTypesList = courseTypesService.getAllTypes();
        }
        if (CollectionUtils.isNotEmpty(courseTypesList)) {
            treeJson = TreeJsonUtil.createCourseTypesTreeJson(courseTypesList);
        }
        return R.ok(treeJson);
    }


    @ApiOperation(value = "新增/修改主分类")
    @PostMapping(value = "/newMainCourseType")
    public R<Object> newMainCourseType(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "分类id") @RequestParam(value = "id", required = false) Long id,
            @ApiParam(value = "分类名称") @RequestParam(value = "courseTypeName") String courseTypeName,
            @ApiParam(value = "分类种类 1.视频课程 2.下载资料") @RequestParam(value = "type", required = false) Integer type,
            @ApiParam(value = "前端展示序号") @RequestParam(value = "showOrder", required = false) Integer showOrder,
            @ApiParam(value = "是否最后一级 0，否 1，是") @RequestParam(value = "levelEnd", required = false) int levelEnd,
            @ApiParam(value = "运营类型") @RequestParam(value = "operationType") String operationType,
            @ApiParam(value = "合作类型") @RequestParam(value = "cooperationType") String cooperationType,
            @ApiParam(value = "科目类型（运营类型是轻量产品加盟时必填）") @RequestParam(value = "subjectType", required = false) String subjectType
    ) {
        if (id == null || id <= 0) {
            // 新增
            Long aLong = courseTypesService.duplicationMainName(null, courseTypeName);
            if (aLong > 0) return R.fail("分类名重复了");
            // 获取最大的主分类展示序号
            int maxShowOrder = courseTypesService.getMaxShowOrder(0L) + 1;

            CourseTypes data = CourseUtil.newMainCourseTypes(
                    courseTypeName, levelEnd, maxShowOrder, type, cooperationType, operationType, subjectType
            );

            courseTypesService.saveOrUpdate(data);
            courseTypesService.updateMainIdAndNodes(data.getId(), String.valueOf(data.getId()).concat("."));
        } else {
            // 修改
            CourseTypes courseTypes = courseTypesService.getById(id);
            if (courseTypes == null) return R.fail("分类获取失败");

            Long aLong = courseTypesService.duplicationMainName(id, courseTypeName);
            if (aLong > 0) return R.fail("分类名重复了");

            if (courseTypeName != null)
                courseTypes.setCourseTypeName(courseTypeName);
            if (showOrder != null)
                courseTypes.setShowOrder(showOrder);
            courseTypes.setCooperationType(NepUtil.nullToZero(cooperationType));
            courseTypes.setOperationType(NepUtil.nullToZero(operationType));
            courseTypes.setSubjectType(NepUtil.nullToZero(subjectType));
            courseTypesService.saveOrUpdate(courseTypes);
        }

        // 清空缓存
        redisService.setNullLike(RedisParam.MAIN_COURSETYPE);
        redisService.setNullLike(RedisParam.CHILD_COURSETYPE);

        return R.ok();
    }


    @ApiOperation(value = "新增/修改子分类")
    @PostMapping(value = "/newChildCourseType")
    public R<Object> newChildCourseType(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "关联分类id") @RequestParam(value = "parentId", required = false) Long parentId,
            @ApiParam(value = "分类id") @RequestParam(value = "id", required = false) Long id,
            @ApiParam(value = "子分类名称") @RequestParam(value = "courseTypeName") String courseTypeName,
            @ApiParam(value = "是否最后一级 0，否 1，是") @RequestParam(value = "levelEnd", required = false) int levelEnd,
            @ApiParam(value = "运营类型") @RequestParam(value = "operationType", required = false) String operationType,
            @ApiParam(value = "合作类型") @RequestParam(value = "cooperationType", required = false) String cooperationType,
            @ApiParam(value = "科目类型（运营类型是轻量产品加盟时必填）") @RequestParam(value = "subjectType", required = false) String subjectType
    ) {
        CourseTypes parentCourseTypes = courseTypesService.getById(parentId);
        if (parentCourseTypes == null) return R.fail("上级分类获取失败");
        if (parentCourseTypes.getLevelEnd().equals(1)) return R.fail("上级分类是最后一级，不能新增子分类");

        CourseTypes mainCourseTypes = courseTypesService.getById(parentCourseTypes.getMainId());
        if (mainCourseTypes == null) return R.fail("主分类获取失败");

        if (id == null || id <= 0) {
            // 新增
            // 获取分类内的最大序号
            int maxShowOrder = courseTypesService.getMaxShowOrder(parentId) + 1;
            // 获取层级序号
            int levelIndex = NepUtil.nullToZero(parentCourseTypes.getLevelIndex()) + 1;
            if (levelEnd != 1) {
                levelEnd = 0;
            }
            CourseTypes childCourseTypes = CourseUtil.newChildCourseTypes(
                    id, mainCourseTypes.getId(), parentId,
                    courseTypeName, maxShowOrder, levelEnd, levelIndex, parentCourseTypes.getType(),
                    cooperationType, operationType, subjectType
            );
            courseTypesService.saveOrUpdate(childCourseTypes);
            courseTypesService.updateNodes(childCourseTypes.getId(), parentCourseTypes.getNodes().concat(String.valueOf(childCourseTypes.getId())).concat("."));
        } else {
            // 修改
            CourseTypes courseTypes = courseTypesService.getById(id);
            if (courseTypes == null) return R.fail("分类获取失败");

            CourseTypes childCourseType = CourseUtil.editChildCourseTypes(
                    courseTypes, courseTypeName, cooperationType, operationType, subjectType
            );
            courseTypesService.saveOrUpdate(childCourseType);
        }
        // 清空缓存
        redisService.setNullLike(RedisParam.MAIN_COURSETYPE);
        redisService.setNullLike(RedisParam.CHILD_COURSETYPE);
        return R.ok();
    }


    @ApiOperation(value = "根据ID获取分类信息")
    @PostMapping(value = "/getById", produces = "application/json; charset=UTF-8")
    public R<Object> getById(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "分类id") @RequestParam(value = "id") Long id
    ) {
        CourseTypes CourseTypes = courseTypesService.getById(id);
        return R.ok(CourseTypes);
    }


    @ApiOperation(value = "更新分类启用状态")
    @PostMapping(value = "/updateEnabled", produces = "application/json; charset=UTF-8")
    public R<Object> updateEnabled(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "分类id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "状态 0.禁用 1.启用") @RequestParam(value = "enabled") Integer enabled
    ) {
        CourseTypes data = courseTypesService.getById(id);
        if (data == null) return R.fail("获取失败");

        if (data.getParentId().equals(0L)) {
            // 如果是主分类，适用其下所有分类
            courseTypesService.updateEnabled(id, enabled);
        } else {
            // 如果是子分类，适用其下所有分类
            courseTypesService.updateEnabledByParentId(id, enabled);
        }

        // 清空缓存
        redisService.setNullLike(RedisParam.MAIN_COURSETYPE);
        redisService.setNullLike(RedisParam.CHILD_COURSETYPE);
        return R.ok();
    }


    @ApiOperation(value = "获取主分类列表")
    @PostMapping(value = "/getMainCourseTypes", produces = "application/json; charset=UTF-8")
    public R<Object> getMainCourseTypes(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName
    ) {
        List<CourseTypes> mainCourseTypes = courseTypesService.getMainCourseTypes(null);
        return R.ok(mainCourseTypes);
    }


    @ApiOperation(value = "删除分类")
    @PostMapping(value = "/dropData", produces = "application/json; charset=UTF-8")
    public R<Object> dropData(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "分类id") @RequestParam(value = "id") Long id
    ) {
        CourseTypes courseTypes = courseTypesService.getById(id);
        if (courseTypes == null) return R.fail("分类获取失败");

        List<CourseTypes> list = courseTypesService.getByNodesNotId(courseTypes.getNodes(), id);
        if (CollectionUtils.isNotEmpty(list)) return R.fail("有子菜单不能删除");

        // 是最后一层
        long courseCnt = courseService.getByTypeIdCnt(id);
        if (courseCnt > 0) return R.fail("分类下有资料不能删除");

        long l = courseTypesService.dropByParentId(id);

        if (l <= 0) return R.fail("删除失败");

        // 清空缓存
        redisService.setNullLike(RedisParam.MAIN_COURSETYPE);
        redisService.setNullLike(RedisParam.CHILD_COURSETYPE);

        return R.ok();
    }


    @ApiOperation(value = "上移/下移")
    @PostMapping(value = "/upOrDown", produces = "application/json; charset=UTF-8")
    public R<Object> upOrDown(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "类型 1.上移 2.下移") @RequestParam(value = "type") Integer type
    ) {
        CourseTypes data = courseTypesService.getById(id);
        if (data == null) return R.fail("分类获取失败");
        if (type.equals(1)) {
            // 上移
            CourseTypes preData = courseTypesService.getLtShowOrder(data.getParentId(), data.getShowOrder());
            if (preData == null) return R.fail("已在最前");
            // 和前一条记录的序号互换
            Integer prevOrderNum = preData.getShowOrder();
            Integer curOrderNum = data.getShowOrder();
            // 序号互换
            courseTypesService.updateShowOrder(preData.getId(), curOrderNum);
            courseTypesService.updateShowOrder(data.getId(), prevOrderNum);
        } else if (type.equals(2)) {
            // 下移
            CourseTypes backData = courseTypesService.getGtShowOrder(data.getParentId(), data.getShowOrder());
            if (backData == null) return R.fail("已在最后");
            // 和后一条记录的序号互换
            Integer backOrderNum = backData.getShowOrder();
            Integer curOrderNum = data.getShowOrder();
            // 序号互换
            courseTypesService.updateShowOrder(backData.getId(), curOrderNum);
            courseTypesService.updateShowOrder(data.getId(), backOrderNum);
        } else {
            return R.fail("类型错误");
        }
        // 清空缓存
        redisService.setNullLike(RedisParam.MAIN_COURSETYPE);
        redisService.setNullLike(RedisParam.CHILD_COURSETYPE);
        return R.ok();
    }

}